import { Module } from 'vuex'
import jsBridge from '@/utils/jsBridge'
import { User, UserInfo, FinanceWallet, PayPasswordModel } from './types'
import GlobalDataProps from '../types'
import http from '@/http/index'
import { api } from '@/http/api'
import { NATIVE_TYPE } from '@/type'
import {
  getLocalToken,
  setLocalToken,
  clearLocalToken,
  getLocalUserInfo,
  setLocalUserInfo,
  clearLocalUserInfo,
  clearLocalLoginStatus,
  clearNewsInfo,
  getSystemConfig,
  setSystemConfig,
  clearSystemConfig
} from '@/store/localstorage'
const user: Module<User, GlobalDataProps> = {
  namespaced: true,
  state: {
    userInfo: {} as UserInfo,
    token: undefined,
    systemConfig: {}
  },
  getters: {
    getToken: (): string | undefined => {
      return getLocalToken()
    },
    getUserInfo: (): UserInfo | undefined => {
      return getLocalUserInfo()
    },
    getSystemConfigs: (state): any => {
      let systemConfig: any = state.systemConfig || {}
      if (JSON.stringify(systemConfig) === '{}') {
        systemConfig = getSystemConfig()
      }
      return systemConfig
    }
  },
  mutations: {
    setToken: (state, data: string | undefined): void => {
      state.token = data
      data ? setLocalToken(data) : clearLocalToken()
    },
    setUserInfo: (state, data: UserInfo): void => {
      state.userInfo = data
      data && data.id ? setLocalUserInfo(data) : clearLocalUserInfo()
    },
    // 设置配置信息
    setSystemConfig: (state, data: any): void => {
      state.systemConfig = data
      setSystemConfig(data)
    }
  },
  actions: {
    // 获取用户信息
    handleGetUserInfo: async ({ commit }: any): Promise<any> => {
      let finalResult: any
      try {
        const result: any = await http({
          method: 'get',
          url: api.getUserInfo
        })
        if (result) {
          commit('setUserInfo', result)
          finalResult = result
        } else {
          commit('setUserInfo', {})
          finalResult = {}
        }
      } catch (e) {
        console.log(`ERROR FROM handleGetUserInfo: ${e}`)
        finalResult = {}
      }
      return finalResult
    },
    // 用户登录
    handleLogin: async ({ commit }: any, data: any): Promise<any> => {
      try {
        const result: any = await http({
          url: api.login,
          method: 'post',
          data
        })
        if (result) {
          commit('setToken', result)
          return result
        } else {
          return undefined
        }
      } catch (e) {
        console.log(`ERROR FROM handleLogin: ${e}`)
      }
    },
    // 用户登出
    handleLogout: async (): Promise<any> => {
      const userInfo = getLocalUserInfo() as UserInfo
      jsBridge.jsCallNative(NATIVE_TYPE.LOGIN_OUT, { id: userInfo?.consignerContact.userId })
      clearLocalToken()
      clearLocalUserInfo()
      clearLocalLoginStatus()
      clearNewsInfo()
    },
    // 获取短信验证码
    handleGetSmsCode: async (state: any, data: any): Promise<any> => {
      try {
        const result = await http<string>({
          url: api.sms,
          method: 'post',
          data
        })
        if (result) {
          return true
        } else {
          return false
        }
      } catch (e) {
        console.log(`ERROR FROM handleGetSmsCode: ${e}`)
      }
    },
    // 获取用户钱包
    handleGetFinanceWalletUser: async (): Promise<FinanceWallet> => {
      let finalResult: FinanceWallet
      try {
        const result = await http({
          url: api.getFinanceWalletUser,
          method: 'get'
        })
        finalResult = result
      } catch (e) {
        console.log(`ERROR FROM handleGetFinanceWalletUser: ${e}`)
        finalResult = {} as FinanceWallet
      }
      return finalResult
    },
    // 注销账户
    handleAccountDestroy: async ({ commit }, data): Promise<boolean> => {
      let finalResult = false
      try {
        await http({
          url: api.accountDestroy,
          method: 'post',
          data
        })
        finalResult = true
      } catch (e) {
        console.log(`ERROR FROM handleAccountDestroy: ${e}`)
      }
      return finalResult
    },
    // 发送账号注销验证码
    handleAccountDestroySms: async (): Promise<boolean> => {
      let finalResult = false
      try {
        await http({
          url: api.accountDestroySms,
          method: 'post'
        })
        finalResult = true
      } catch (e) {
        console.log(`ERROR FROM handleAccountDestroySms: ${e}`)
      }
      return finalResult
    },
    handleInitSystemTel: async ({ commit }): Promise<any> => {
      let finalResult = ''
      try {
        const result = await http({
          url: api.systemConfigTel,
          method: 'get'
        })
        commit('setSystemConfig', { tel: result })
        finalResult = result
      } catch (e) {
        console.log(`ERROR FROM handleInitSystemTel: ${e}`)
      }
      return finalResult
    },
    // 判断是否设置了支付密码
    handleFinanceWalletPayPasswordStatus: async ({ commit }): Promise<any> => {
      let finalResult = {}
      try {
        const result = await http({
          url: api.financeWalletPayPasswordStatus,
          method: 'get'
        })
        finalResult = result
      } catch (e) {
        console.log(`ERROR FROM handleInitSystemTel: ${e}`)
      }
      return finalResult
    },
    handleSetFinanceWalletDriverPayPassword: async ({ commit }: any, data: PayPasswordModel): Promise<boolean> => {
      let finalResult = false
      try {
        await http({
          url: api.setFinanceWalletDriverPayPassword,
          method: 'post',
          data
        })
        finalResult = true
      } catch (e) {
        console.log(`ERROR FROM handleSetFinanceWalletDriverPayPassword: ${e}`)
      }
      return finalResult
    },
    // 意见反馈
    handleAddUserOpinion: async ({ commit }: any, data: string): Promise<boolean> => {
      let finalResult = false
      try {
        await http({
          url: api.addUserOpinion,
          method: 'post',
          data: {
            remark: data
          }
        })
        finalResult = true
      } catch (e) {
        console.log(`ERROR FROM handleAddUserOpinion: ${e}`)
      }
      return finalResult
    }
  }
}

export default user
